const SecretTool = require('../utils/SecretTool')
const wxchatLogin = require('../config/wxLogin')
const BackCode = require("../utils/BackCode");
const WxDataTool = require("../utils/WxDataTool");
const redisConfig = require('../config/RedisConfig')
const DB = require('../config/Sequelize')
const RandomTool = require("../utils/RandomTool");


const WxLoginService = {
    wx_insert: (signature, timestamp, nonce, echostr) => {
        const token = 'testxdclass'
        let str = SecretTool.sha1([token, timestamp, nonce].sort().join(''))
        if (str === signature) {
            return true
        }
        return false
    },
    login: async () => {
        const { qrcodeUrl, ticket } = await wxchatLogin.getOR()
        let key = `wechat:ticket:${ticket}`
        redisConfig.set(key, JSON.stringify({ isScan: 'no' }, 120))
        return BackCode.buildSuccessAndData({ data: { qrcodeUrl, ticket } })
    },
    wx_message: async (req) => {
        let xmData = await WxDataTool.getXmlStr(req)
        let objectData = await WxDataTool.getObject(xmData)
        let lastData = await WxDataTool.getLastData(objectData.xml)

        //随机生成用户的头像和昵称
        let head_img = RandomTool.randomAvatar()
        let username = RandomTool.randomName()
        let user = null
        //    判断openId是否注册过
        const openidRes = await DB.Account.findAll({ where: { openid: objectData.FromUserName }, raw: true })
        if (openidRes.length === 0) {
            let resData = DB.Account.create({ username, head_img, openid: objectData.FromUserName })
            user = { head_imgm, username, id: resData.toJSON().id }
        } else {
            user = { head_img: openidRes[0].head_img, username: openidRes[0].username, id: openidRes[0].id }
        }
        // 生成token
        let token = SecretTool.jwtSign(user, '168h')

        // 更新redis状态
        let key = `wechat:ticket:${lastData.Ticket}`
        const existsKey = await redisConfig.exists(key)
        if (existsKey) {
            redisConfig.set(key, JSON.stringify({ isScan: 'yes', token }, 120))
        }
        let content = ''
        if (lastData.MsgType == 'event') {
            if (lastData.Event = 'SCAN') {
                content = '欢迎回来，讲师微信：xdclass6'
            } else if (lastData.Event = 'subscribe') {
                content = '感谢关注，讲师微信：xdclass6'
            }

            let msgStr = `<xml>
        <ToUserName><![CDATA[${lastData.FromUserName}]]></ToUserName>
        <FromUserName><![CDATA[${lastData.ToUserName}]]></FromUserName>
        <CreateTime>${Date.now()}</CreateTime>
        <MsgType><![CDATA[text]]></MsgType>
        <Content><![CDATA[${content}]]></Content>
       </xml>`
            return msgStr
        }
    },
    check_scan: async (ticket) => {
        let key = `wechat:ticket:${ticket}`
        const redisData = JSON.parse(await redisConfig.get(key))
        if (redisData.isScan === 'no') {
            return BackCode.buildResult(WECHAT_WAIT_SCAN)
        }
        if (redisData.isScan === 'yes') {
            let token = redisData.token
            return BackCode.buildSuccessAndData({ data: `Bearer ${token}` })
        }
        return
    }
}
module.exports = WxLoginService